#region Summary

// 
// Owner : JackieHan 
// 
// Solution : DailyCollection 
// 
// Project : Jackie.Utility.Compiler
// 
// File : KeyWord.cs
// 
// CopyRight : Copyright © 2010-2011 Skomart Corporation, All Rights Reserved 
// 
// Summary : 关键字定义
// 
// History : 
//			2011-05-31 15:13:38	    Create 
// 

#endregion

#region Using

using System;
using System.Collections.Generic;
using System.Linq;
using Jackie.Utility.CustomExtension;

#endregion

namespace Jackie.Utility.Compiler.Scanner
{
    /// <summary> 
    /// 关键字定义
    /// </summary>
    public class KeyWord
    {
        private readonly IDictionary<string, Token> keyWords;


        public KeyWord()
        {
            keyWords = new Dictionary<string, Token>
                              {
                                  {"set", new Token(TokenType.SetKeyWord)},
                                  {"var",new Token(TokenType.VarKeyWord)},
                                  {"if",new Token(TokenType.IfKeyWord)},
                                  {"else",new Token(TokenType.ElseKeyWord)},
                                  {"for",new Token(TokenType.ForKeyWord)}
                              };
        }

        /// <summary>
        /// 获取判断是否为关键字的条件
        /// </summary>
        /// <param name="keyWordState">状态</param>
        /// <returns></returns>
        public string GetJudgement(State keyWordState)
        {
            string judgementStr;
            switch (keyWordState)
            {
                case State.KeyWord1:
                    judgementStr = Get(0);
                    break;
                case State.KeyWord2:
                    judgementStr = Get(1);
                    break;
                case State.KeyWord3:
                    judgementStr = Get(2);
                    break;
                case State.KeyWord4:
                    judgementStr = Get(3);
                    break;
                case State.KeyWord5:
                    judgementStr = Get(4);
                    break;
                default:
                    throw new System.Exception("not suport state:" + keyWordState);
            }
            return judgementStr;
        }

        private string Get(int level)
        {
            var str = string.Empty;
            keyWords.Keys.ForEach(item => { if (item.Length >= level + 1) str += item[level]; });
            return str;
        }

        /// <summary>
        /// 根据读取到的字符匹配关键字
        /// </summary>
        /// <param name="readedStr"></param>
        /// <returns></returns>
        public Token GetToken(string readedStr)
        {
            var matchedKeyWord = keyWords.Keys.FirstOrDefault(item => item.Equals(readedStr));
            return string.IsNullOrEmpty(matchedKeyWord) ? null : keyWords[matchedKeyWord];
        }
    }
}